package com.adk.backend.controller;

import com.adk.backend.annotation.RequiresPermission;
import com.adk.backend.common.Result;
import com.adk.backend.entity.LxCustomList;
import com.adk.backend.service.CustomListService;
import com.adk.backend.util.ExcelUtil;
import com.adk.backend.util.FileUploadUtil;
import com.adk.backend.util.JwtUtil;
import com.adk.backend.util.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 投递单管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/do")
public class CustomListController {
    
    @Autowired
    private CustomListService customListService;
    
    @Autowired
    private FileUploadUtil fileUploadUtil;
    
    @Autowired
    private LogUtil logUtil;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private ExcelUtil excelUtil;
    
    /**
     * 查询投递单列表
     */
    @RequiresPermission("list")
    @GetMapping("/list")
    public Result<List<Map<String, Object>>> getCustomList(
            @RequestParam(required = false) Long customerId,
            @RequestParam(required = false) Integer recvd,
            @RequestParam(required = false) String months,
            @RequestHeader(value = "Authorization", required = false) String token) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("customerId", customerId);
            params.put("recvd", recvd);
            
            // 处理月份筛选
            if (months != null && !months.isEmpty()) {
                try {
                    LocalDate monthDate = LocalDate.parse(months + "-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                    int startDateInt = (int) monthDate.atStartOfDay().atZone(java.time.ZoneId.systemDefault()).toEpochSecond();
                    int endDateInt = (int) monthDate.plusMonths(1).atStartOfDay().atZone(java.time.ZoneId.systemDefault()).toEpochSecond() - 1;
                    params.put("startDateInt", startDateInt);
                    params.put("endDateInt", endDateInt);
                } catch (Exception e) {
                    log.warn("月份格式错误: {}", months, e);
                }
            }
            
            List<Map<String, Object>> list = customListService.getCustomList(params);
            return Result.success(list);
        } catch (Exception e) {
            log.error("查询投递单列表失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取月份列表
     */
    @GetMapping("/months")
    public Result<List<String>> getMonthList() {
        try {
            List<String> months = customListService.getMonthList();
            return Result.success(months);
        } catch (Exception e) {
            log.error("获取月份列表失败", e);
            return Result.error("获取失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID查询投递单详情
     */
    @RequiresPermission("view")
    @GetMapping("/detail")
    public Result<Map<String, Object>> getCustomListDetail(@RequestParam Long id) {
        try {
            Map<String, Object> detail = customListService.getCustomListDetailById(id);
            if (detail == null) {
                return Result.error("投递单不存在");
            }
            return Result.success(detail);
        } catch (Exception e) {
            log.error("查询投递单详情失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 保存投递单（新增或更新）
     */
    @RequiresPermission("edit")
    @PostMapping("/save")
    public Result<Boolean> saveCustomList(
            @RequestParam(required = false) Long id,
            @RequestParam String ibDate,
            @RequestParam Long customerId,
            @RequestParam String blNo,
            @RequestParam Integer ctns,
            @RequestParam java.math.BigDecimal shipWeigth,
            @RequestParam java.math.BigDecimal totalFee,
            @RequestParam(required = false) MultipartFile[] attrFiles,
            @RequestParam(required = false) MultipartFile[] attrBlFiles,
            @RequestParam(required = false) String remarks,
            @RequestHeader(value = "Authorization", required = false) String token,
            HttpServletRequest request) {
        try {
            // 获取当前用户ID（从token中获取）
            Integer userId = getCurrentUserId(token);
            
            LxCustomList customList = new LxCustomList();
            if (id != null && id > 0) {
                customList.setId(id);
                // 查询现有记录
                Map<String, Object> existing = customListService.getCustomListDetailById(id);
                if (existing == null) {
                    return Result.error("投递单不存在");
                }
                customList.setUpdateUid(userId);
                customList.setUpdateTime((int) (System.currentTimeMillis() / 1000));
            } else {
                customList.setAddUid(userId);
                customList.setAddTime((int) (System.currentTimeMillis() / 1000));
            }
            
            customList.setIbDate(ibDate);
            customList.setCustomerId(customerId);
            customList.setBlNo(blNo);
            customList.setCtns(ctns);
            customList.setShipWeigth(shipWeigth);
            customList.setTotalFee(totalFee);
            customList.setRemarks(remarks);
            
            // 处理入库日期时间戳
            try {
                LocalDate date = LocalDate.parse(ibDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                customList.setIbDateInt((int) (date.atStartOfDay().atZone(java.time.ZoneId.systemDefault()).toEpochSecond()));
            } catch (Exception e) {
                log.warn("日期格式转换失败: {}", ibDate, e);
            }
            
            // 处理清单文件上传
            if (attrFiles != null && attrFiles.length > 0) {
                List<String> fileUrls = new ArrayList<>();
                for (MultipartFile file : attrFiles) {
                    if (!file.isEmpty()) {
                        String fileUrl = fileUploadUtil.uploadFileToLocal(file, "uploads/do", userId, "pl");
                        fileUrls.add(fileUrl);
                    }
                }
                if (!fileUrls.isEmpty()) {
                    // 如果是更新，需要删除旧文件
                    if (id != null && id > 0) {
                        Map<String, Object> existing = customListService.getCustomListDetailById(id);
                        if (existing != null && existing.get("attrList") != null) {
                            String oldAttrList = (String) existing.get("attrList");
                            if (oldAttrList != null && !oldAttrList.isEmpty()) {
                                String[] oldFiles = oldAttrList.split(",");
                                for (String oldFile : oldFiles) {
                                    if (oldFile != null && !oldFile.trim().isEmpty()) {
                                        fileUploadUtil.deleteLocalFile(oldFile.trim());
                                    }
                                }
                            }
                        }
                    }
                    customList.setAttrList(String.join(",", fileUrls));
                }
            }
            
            // 处理提单文件上传
            if (attrBlFiles != null && attrBlFiles.length > 0) {
                List<String> fileUrls = new ArrayList<>();
                for (MultipartFile file : attrBlFiles) {
                    if (!file.isEmpty()) {
                        String fileUrl = fileUploadUtil.uploadFileToLocal(file, "uploads/do", userId, "bl");
                        fileUrls.add(fileUrl);
                    }
                }
                if (!fileUrls.isEmpty()) {
                    // 如果是更新，需要删除旧文件
                    if (id != null && id > 0) {
                        Map<String, Object> existing = customListService.getCustomListDetailById(id);
                        if (existing != null && existing.get("attrBl") != null) {
                            String oldAttrBl = (String) existing.get("attrBl");
                            if (oldAttrBl != null && !oldAttrBl.isEmpty()) {
                                String[] oldFiles = oldAttrBl.split(",");
                                for (String oldFile : oldFiles) {
                                    if (oldFile != null && !oldFile.trim().isEmpty()) {
                                        fileUploadUtil.deleteLocalFile(oldFile.trim());
                                    }
                                }
                            }
                        }
                    }
                    customList.setAttrBl(String.join(",", fileUrls));
                }
            }
            
            boolean success = customListService.saveCustomList(customList);
            if (success) {
                logUtil.logAction(getCurrentUserIdLong(token), null, "custom_list", customList.getId(), 
                    id != null && id > 0 ? "修改投递单" : "添加投递单", request);
                return Result.success(id != null && id > 0 ? "修改成功" : "添加成功", true);
            } else {
                return Result.error("保存失败");
            }
        } catch (Exception e) {
            log.error("保存投递单失败", e);
            return Result.error("保存失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除投递单
     */
    @RequiresPermission("del")
    @PostMapping("/del")
    public Result<Boolean> deleteCustomList(
            @RequestParam Long id,
            @RequestHeader(value = "Authorization", required = false) String token,
            HttpServletRequest request) {
        try {
            // 删除关联的文件
            Map<String, Object> detail = customListService.getCustomListDetailById(id);
            if (detail != null) {
                // 删除清单文件
                if (detail.get("attrList") != null) {
                    String attrList = (String) detail.get("attrList");
                    if (attrList != null && !attrList.isEmpty()) {
                        String[] files = attrList.split(",");
                        for (String file : files) {
                            if (file != null && !file.trim().isEmpty()) {
                                fileUploadUtil.deleteLocalFile(file.trim());
                            }
                        }
                    }
                }
                // 删除提单文件
                if (detail.get("attrBl") != null) {
                    String attrBl = (String) detail.get("attrBl");
                    if (attrBl != null && !attrBl.isEmpty()) {
                        String[] files = attrBl.split(",");
                        for (String file : files) {
                            if (file != null && !file.trim().isEmpty()) {
                                fileUploadUtil.deleteLocalFile(file.trim());
                            }
                        }
                    }
                }
                // 删除POD文件
                if (detail.get("pod") != null) {
                    String pod = (String) detail.get("pod");
                    if (pod != null && !pod.isEmpty()) {
                        String[] files = pod.split(",");
                        for (String file : files) {
                            if (file != null && !file.trim().isEmpty()) {
                                fileUploadUtil.deleteLocalFile(file.trim());
                            }
                        }
                    }
                }
            }
            
            boolean success = customListService.deleteCustomList(id);
            if (success) {
                logUtil.logAction(getCurrentUserIdLong(token), null, "custom_list", id, "删除投递单", request);
                return Result.success("删除成功", true);
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            log.error("删除投递单失败", e);
            return Result.error("删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 保存POD签收信息
     */
    @RequiresPermission("pod")
    @PostMapping("/savepod")
    public Result<Boolean> savePodInfo(
            @RequestParam Long id,
            @RequestParam Integer recvType,
            @RequestParam(required = false) String recvNo,
            @RequestParam String recvDate,
            @RequestParam(required = false) MultipartFile[] podFiles,
            @RequestParam(required = false) String remarks,
            @RequestHeader(value = "Authorization", required = false) String token,
            HttpServletRequest request) {
        try {
            Integer userId = getCurrentUserId(token);
            
            // 处理POD文件上传
            String pod = null;
            if (podFiles != null && podFiles.length > 0) {
                List<String> fileUrls = new ArrayList<>();
                for (MultipartFile file : podFiles) {
                    if (!file.isEmpty()) {
                        String fileUrl = fileUploadUtil.uploadFileToLocal(file, "uploads/do", userId, null);
                        // 保持与清单和提单文件格式一致（使用 ./uploads/do/ 格式）
                        fileUrls.add(fileUrl);
                    }
                }
                if (!fileUrls.isEmpty()) {
                    pod = String.join(",", fileUrls);
                }
            }
            
            boolean success = customListService.updatePodInfo(id, recvType, recvNo, recvDate, pod, remarks, userId);
            if (success) {
                logUtil.logAction(getCurrentUserIdLong(token), null, "custom_list", id, "上传POD签收单", request);
                return Result.success("操作成功", true);
            } else {
                return Result.error("操作失败");
            }
        } catch (Exception e) {
            log.error("保存POD信息失败", e);
            return Result.error("操作失败：" + e.getMessage());
        }
    }
    
    /**
     * 文件预览/下载接口（带权限控制）
     */
    @RequiresPermission("view")
    @GetMapping("/file")
    public ResponseEntity<Resource> previewOrDownloadFile(
            @RequestParam String filePath,
            @RequestParam(required = false, defaultValue = "false") Boolean download,
            @RequestHeader(value = "Authorization", required = false) String token) {
        try {
            // 验证文件路径是否合法（防止路径遍历攻击）
            String cleanPath = filePath.startsWith("./") ? filePath.substring(2) : filePath;
            if (cleanPath.contains("..") || !cleanPath.startsWith("uploads/do/")) {
                return ResponseEntity.badRequest().build();
            }
            
            File file = new File(cleanPath);
            if (!file.exists() || !file.isFile()) {
                return ResponseEntity.notFound().build();
            }
            
            Resource resource = new FileSystemResource(file);
            String fileName = file.getName();
            
            // 根据文件扩展名确定Content-Type
            String contentType = "application/octet-stream";
            String lowerFileName = fileName.toLowerCase();
            if (lowerFileName.endsWith(".jpg") || lowerFileName.endsWith(".jpeg")) {
                contentType = "image/jpeg";
            } else if (lowerFileName.endsWith(".png")) {
                contentType = "image/png";
            } else if (lowerFileName.endsWith(".pdf")) {
                contentType = "application/pdf";
            } else if (lowerFileName.endsWith(".xls") || lowerFileName.endsWith(".xlsx")) {
                contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            } else if (lowerFileName.endsWith(".txt")) {
                contentType = "text/plain";
            } else if (lowerFileName.endsWith(".csv")) {
                contentType = "text/csv";
            }
            
            HttpHeaders headers = new HttpHeaders();
            if (download) {
                headers.setContentDispositionFormData("attachment", fileName);
            } else {
                headers.setContentDispositionFormData("inline", fileName);
            }
            headers.setContentType(MediaType.parseMediaType(contentType));
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);
        } catch (Exception e) {
            log.error("文件访问失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 下载投递单文件（打包成ZIP）
     */
    @RequiresPermission("view")
    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFiles(@RequestParam Long id) {
        try {
            Map<String, Object> detail = customListService.getCustomListDetailById(id);
            if (detail == null) {
                return ResponseEntity.notFound().build();
            }
            
            List<String> filePaths = new ArrayList<>();
            
            // 添加清单文件
            if (detail.get("attrList") != null) {
                String attrList = (String) detail.get("attrList");
                if (attrList != null && !attrList.isEmpty()) {
                    String[] files = attrList.split(",");
                    for (String file : files) {
                        if (file != null && !file.trim().isEmpty()) {
                            filePaths.add(file.trim());
                        }
                    }
                }
            }
            
            // 添加提单文件
            if (detail.get("attrBl") != null) {
                String attrBl = (String) detail.get("attrBl");
                if (attrBl != null && !attrBl.isEmpty()) {
                    String[] files = attrBl.split(",");
                    for (String file : files) {
                        if (file != null && !file.trim().isEmpty()) {
                            filePaths.add(file.trim());
                        }
                    }
                }
            }
            
            if (filePaths.isEmpty()) {
                return ResponseEntity.notFound().build();
            }
            
            // 创建临时ZIP文件
            String zipFileName = "uploads/tmp/" + System.currentTimeMillis() + "_" + id + ".zip";
            File zipFile = fileUploadUtil.createZipFile(filePaths, zipFileName);
            
            Resource resource = new FileSystemResource(zipFile);
            String downloadFileName = "custom_" + id + "_" + System.currentTimeMillis() + ".zip";
            
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + downloadFileName + "\"")
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
        } catch (Exception e) {
            log.error("下载文件失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 获取当前用户ID（从token中获取）
     */
    private Integer getCurrentUserId(String token) {
        try {
            if (token != null && !token.isEmpty()) {
                // 移除 "Bearer " 前缀（如果有）
                if (token.startsWith("Bearer ")) {
                    token = token.substring(7);
                }
                Long userId = jwtUtil.getUserIdFromToken(token);
                return userId != null ? userId.intValue() : 1;
            }
        } catch (Exception e) {
            log.warn("获取用户ID失败", e);
        }
        // 默认返回1（开发环境）
        return 1;
    }
    
    private Long getCurrentUserIdLong(String token) {
        Integer userId = getCurrentUserId(token);
        return userId != null ? userId.longValue() : null;
    }
    
    /**
     * 批量删除投递单
     */
    @RequiresPermission("del")
    @PostMapping("/batch-del")
    public Result<Boolean> batchDeleteCustomList(
            @RequestParam("ids") List<Long> ids,
            @RequestHeader(value = "Authorization", required = false) String token,
            HttpServletRequest request) {
        try {
            int successCount = 0;
            int failCount = 0;
            
            for (Long id : ids) {
                try {
                    // 删除关联的文件
                    Map<String, Object> detail = customListService.getCustomListDetailById(id);
                    if (detail != null) {
                        // 删除清单文件
                        if (detail.get("attrList") != null) {
                            String attrList = (String) detail.get("attrList");
                            if (attrList != null && !attrList.isEmpty()) {
                                String[] files = attrList.split(",");
                                for (String file : files) {
                                    if (file != null && !file.trim().isEmpty()) {
                                        fileUploadUtil.deleteLocalFile(file.trim());
                                    }
                                }
                            }
                        }
                        // 删除提单文件
                        if (detail.get("attrBl") != null) {
                            String attrBl = (String) detail.get("attrBl");
                            if (attrBl != null && !attrBl.isEmpty()) {
                                String[] files = attrBl.split(",");
                                for (String file : files) {
                                    if (file != null && !file.trim().isEmpty()) {
                                        fileUploadUtil.deleteLocalFile(file.trim());
                                    }
                                }
                            }
                        }
                        // 删除POD文件
                        if (detail.get("pod") != null) {
                            String pod = (String) detail.get("pod");
                            if (pod != null && !pod.isEmpty()) {
                                String[] files = pod.split(",");
                                for (String file : files) {
                                    if (file != null && !file.trim().isEmpty()) {
                                        fileUploadUtil.deleteLocalFile(file.trim());
                                    }
                                }
                            }
                        }
                    }
                    
                    boolean success = customListService.deleteCustomList(id);
                    if (success) {
                        successCount++;
                        logUtil.logAction(getCurrentUserIdLong(token), null, "custom_list", id, "批量删除投递单", request);
                    } else {
                        failCount++;
                    }
                } catch (Exception e) {
                    log.error("删除投递单失败: {}", id, e);
                    failCount++;
                }
            }
            
            if (failCount == 0) {
                return Result.success("成功删除 " + successCount + " 条记录", true);
            } else {
                return Result.error("成功删除 " + successCount + " 条记录，失败 " + failCount + " 条记录");
            }
        } catch (Exception e) {
            log.error("批量删除投递单失败", e);
            return Result.error("批量删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 导出投递单列表（Excel）
     */
    @RequiresPermission("list")
    @PostMapping("/export")
    public void exportCustomList(
            @RequestParam(required = false) Long customerId,
            @RequestParam(required = false) Integer recvd,
            @RequestParam(required = false) String months,
            HttpServletResponse response) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("customerId", customerId);
            params.put("recvd", recvd);
            
            // 处理月份筛选
            if (months != null && !months.isEmpty()) {
                try {
                    LocalDate monthDate = LocalDate.parse(months + "-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                    int startDateInt = (int) monthDate.atStartOfDay().atZone(java.time.ZoneId.systemDefault()).toEpochSecond();
                    int endDateInt = (int) monthDate.plusMonths(1).atStartOfDay().atZone(java.time.ZoneId.systemDefault()).toEpochSecond() - 1;
                    params.put("startDateInt", startDateInt);
                    params.put("endDateInt", endDateInt);
                } catch (Exception e) {
                    log.warn("月份格式错误: {}", months, e);
                }
            }
            
            List<Map<String, Object>> list = customListService.getCustomList(params);
            
            // 准备表头
            String[] headers = {
                "#", "入库日期", "客户代码", "客户简称", "提单号", "箱数", 
                "计费重", "实际申报金额", "签收状态", "签收日期", "添加时间"
            };
            
            // 转换数据格式
            List<Map<String, Object>> exportData = new ArrayList<>();
            for (Map<String, Object> item : list) {
                Map<String, Object> row = new HashMap<>();
                row.put("#", item.get("id"));
                row.put("入库日期", item.get("ibDate"));
                row.put("客户代码", item.get("cusCode"));
                row.put("客户简称", item.get("cusShort"));
                row.put("提单号", item.get("blNo"));
                row.put("箱数", item.get("ctns"));
                row.put("计费重", item.get("shipWeigth"));
                row.put("实际申报金额", item.get("totalFee"));
                row.put("签收状态", (item.get("recvd") != null && ((Number) item.get("recvd")).intValue() == 2) ? "已签收" : "未签收");
                row.put("签收日期", item.get("recvDate"));
                if (item.get("addTime") != null) {
                    java.time.Instant instant = java.time.Instant.ofEpochSecond(((Number) item.get("addTime")).longValue());
                    row.put("添加时间", java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(java.time.ZonedDateTime.ofInstant(instant, java.time.ZoneId.systemDefault())));
                } else {
                    row.put("添加时间", "");
                }
                exportData.add(row);
            }
            
            // 生成文件名
            String fileName = "投递单列表_" + java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss").format(java.time.LocalDateTime.now());
            
            // 导出Excel
            excelUtil.exportExcel(response, fileName, headers, exportData);
        } catch (Exception e) {
            log.error("导出投递单列表失败", e);
            try {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write("导出失败：" + e.getMessage());
            } catch (IOException ex) {
                log.error("写入错误响应失败", ex);
            }
        }
    }
}

